package cn.tedu.myweb.myweb.filter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.tedu.myweb.myweb.util.Mime;

@WebFilter(value= {"*.ts","*.key"})
public class ForwardFilter implements Filter{


	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest Httprequest = (HttpServletRequest) request;
		HttpServletResponse Httpresponse = (HttpServletResponse) response;
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String url = Httprequest.getRequestURI();
		int index = url.indexOf(".");
		if(index != -1){
			Httpresponse.setContentType(Mime.getMime(url.substring(index)));
		}
		
		System.err.println(url);
		
		OutputStream out = Httpresponse.getOutputStream();
		byte[] data =getData(url);
		Httpresponse.setContentLength(data.length);
		out.write(data);
		out.close();
		
	}
	
	public byte[] getData(String url) {
		byte[] data = new byte[0];
		try{
			HttpURLConnection conn = (HttpURLConnection)getUrl(url).openConnection();
			//设置超时间为3秒
			conn.setConnectTimeout(1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
			conn.setRequestProperty("Origin","http://tts.tmooc.cn");
			conn.setRequestProperty("Referer","http://tts.tmooc.cn/video/showVideo?menuId=605103&version=JSD_N_V09");
			conn.setRequestProperty("Host","c.it211.com.cn");
			//得到输入流
			InputStream in = conn.getInputStream();
			byte[] buffer = new byte[1024*4];
			int bytesRead = 0;
			while((bytesRead=in.read(buffer))!=-1) {
				int old = data.length;
				data = Arrays.copyOf(data, data.length+bytesRead);
				for(int i = 0;i<bytesRead;i++) {
					data[old+i] =buffer[i];
				}
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	public URL getUrl(String url) throws MalformedURLException {
		return new URL("http://c.it211.com.cn"+url);
	}


}
